package com.quizh.login.core;

import static com.googlecode.objectify.ObjectifyService.ofy;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.Cursor;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.cmd.LoadType;

public abstract class BaseDAO<T extends BaseVO> {
	private Class<? extends BaseVO> entity = getVoClass();
	private Class<? extends BaseBean> entityBean = getBeanClass();

	@SuppressWarnings("unchecked")
	public <B extends BaseBean> B get(String webSafeString) {
		T vo = (T) ofy().load().key(Key.valueOf(webSafeString)).now();
		B bean = vo.voToBean();
		bean.setKey(webSafeString);
		return bean;
	}
	
	public <B extends BaseBean> B put(B bean) {
		Key<BaseVO> value = ofy().save().entity(bean.beanToVo()).now();
		bean.setKey(value.getString());
		return bean;
	}
	

	public void put(List<? extends BaseBean>  beanList) {
		List<BaseVO> vo = new ArrayList<BaseVO>();
		for (BaseBean bean : beanList) {
			vo.add(bean.beanToVo());
		}
		 ofy().save().entities(vo).now();
	}
	
	
	public BaseList<? extends BaseBean> search(List<FilterBean> filters, String cursor, int limit, String order) {
		LoadType<? extends BaseVO> se = ofy().load().type(getVoClass());
		for (FilterBean filterBean : filters) {
			se.filter(filterBean.getAtt(), filterBean.getValue());
		}
		se.limit(limit);
		Cursor adsf = Cursor.fromWebSafeString(cursor);
		se.startAt(adsf );
		List<? extends BaseVO> values = se.list();
		values.get(0).voToBean();
		return null;
	}
	
	protected abstract Class<? extends BaseVO> getVoClass();
	protected abstract Class<? extends BaseBean> getBeanClass();
}
